<script setup lang="ts">
import { computed, onMounted, reactive, ref, shallowRef, watch, watchEffect } from 'vue';
import { $t } from '@/locales';
import { ApiMenuItem, ApimenuserviceApi, ApiroleserviceApi } from '@/api-services';
import { feature, getAPI } from '@/axios-utils';
import { queryDone } from '@/utils/api';
import { Tree } from 'element-plus/es/components/tree-v2/src/types';



defineOptions({
  name: 'RoleMenuTree'
});

// interface Props {
//   roleId: number;
// }

// const props = defineProps<Props>();



const roleId = defineModel<number>('roleId',
  { default: 0 }
)

// watch(roleId, async (val) => {
//   console.log('watchRoleId')
//   if (val != 0) {
//     await getChecks(val);
//   }
// })



watchEffect(() => {
  const _roleId = roleId.value;
  if (_roleId && _roleId != 0) {
    getChecks(roleId.value);
  }
})


interface DataNode {
  id: number | undefined;
  title?: string | null;
  svgIcon?: string;
  children?: DataNode[];
}
const props = {
  label: 'title',
  children: 'children',
}
const treeData = shallowRef<DataNode[]>([]);

async function getTreeList() {

  const [err, res] = await feature(getAPI(ApimenuserviceApi).getActionTreeList());
  queryDone(err, () => {
    if (res?.data.data) {
      treeData.value = recursiveTransform(res.data.data);
    }
  })
}
//全部菜单和方法的id
const allActionIds = ref<number[]>([]);
function recursiveTransform(data: ApiMenuItem[]): DataNode[] {
  return data.map(item => {
    const { id: id, name, isPermission, pgType } = item;

    const _pgType = pgType as unknown as number;

    let icon = '';
    switch (_pgType) {
      case 0: icon = 'mdi:format-list-bulleted'; break;
      case 100: icon = 'carbon:document'; break;
      case 200: icon = 'carbon:document'; break;
      case 300: icon = 'mdi:code-braces'; break;
    }
    if (_pgType == 300) {
      allActionIds.value.push(id!);
    }



    let node: DataNode = {
      id: id,
      title: item.name,
      svgIcon: icon,
    }

    //是否有子节点
    if (item.children) {
      node.children = recursiveTransform(item.children);
    }

    return node;
  });
}
// 添加Key和CheckInfo类型定义
type Key = string | number;
interface CheckInfo {
  halfCheckedKeys?: Key[];
}


// const checks = shallowRef<number[]>([]);
const emit = defineEmits(['updateCheck']);
// const treeChecked = reactive<{ checked: (number | string)[], halfChecked: (number | string)[] }>({ checked: [], halfChecked: [] });
const roleMenuTree = ref();
const handleCheckChange = (
  data: Tree,
  checked: boolean,
  indeterminate: boolean
) => {
  // console.log(data, checked, indeterminate);

  //获取有哪几个节点被选中了


  const sumChecked = roleMenuTree.value.getCheckedKeys() as number[];
  //获取allMenuIds和sumChecked的交集
  const intersection = sumChecked.filter(item => allActionIds.value.includes(item as number));
  emit('updateCheck', intersection);

}
// const handleSelectTree = (checked: Key[] | { checked: Key[]; halfChecked: Key[]; }, info: CheckInfo) => {
//   console.log('handleSelectTree', checked, info);

//   if (Array.isArray(checked)) {
//     treeChecked.checked = checked;
//     if (info.halfCheckedKeys) {
//       treeChecked.halfChecked = info.halfCheckedKeys
//     }
//   } else {
//     treeChecked.checked = checked.checked;
//     treeChecked.halfChecked = checked.halfChecked;
//   }

//   const sumChecked = [...treeChecked.checked, ...treeChecked.halfChecked]
//   //获取allMenuIds和sumChecked的交集
//   const intersection = sumChecked.filter(item => allActionIds.value.includes(item as number));
//   emit('updateCheck', intersection);
// }
// const treeChecked = ref<number[]>([]);
async function getChecks(roleId: number) {
  const [err, res] = await feature(getAPI(ApiroleserviceApi).getRoleMenuRight(roleId));

  queryDone(err, () => {
    if (res?.data.data) {

      roleMenuTree.value.setCheckedKeys(res.data.data)
      // treeChecked.value = res.data.data;

    }
  })
  // request
}




// async function handleSubmit() {
//   console.log(checks.value, roleId);
//   // request
//   const roleMenuInput: ApiRoleMenuInput = {
//     roleId: roleId.value,
//     menuIds: checks.value,
//     //@ts-ignore
//     pgType: 300,
//   }
//   const [err, res] = await feature(getAPI(ApiroleserviceApi).setRoleMenuRight(roleMenuInput));

//   queryDone(err, () => {
//     if (res?.data.data) {

//       window.$message?.success?.($t('common.modifySuccess'));


//     } else {
//       window.$message?.error?.($t('common.error'));

//     }
//   })

// }


onMounted(() => {
  getTreeList();
})

</script>

<template>
  <ElTree ref="roleMenuTree" :props="props" show-checkbox :data="treeData" node-key="id"
    @check-change="handleCheckChange">
    <template #="{ node, data }">
      <ElSpace>
        <SvgIcon :icon="data.svgIcon"></SvgIcon>
        <p>{{ data.title }}</p>
      </ElSpace>
    </template>
  </ElTree>
</template>

<style scoped></style>
